package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.BaseBusinessException;
//import com.cskaoyan.shopping.dal.entitys.Stock;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.shopping.constants.ShoppingRetCode;
import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.form.CartRequest;
import com.cskaoyan.shopping.form.CheckAllItemRequest;
import com.cskaoyan.shopping.remote.CartApiClient;
import com.cskaoyan.shopping.service.ICartService;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author : bunnyupup
 * @description :
 * @date : Created in 2022/8/24 23:31
 */
@Service
public class CbjCartServiceImpl implements ICartService {
    @Autowired
    ItemMapper itemMapper;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    CartItemConverter cartItemConverter;

//    @Autowired
//    StockMapper stockMapper;

    @Autowired
    CartApiClient cartApiClient;


    @Override
    public List<CartProductDto> getCartListById(Long userId) {
        List<CartProductDto> cartList = new ArrayList<>();
        // 读取redis购物车
        String userCartName = "Cart" + userId;
        RMap<Long, CartProductDto> map = redissonClient.getMap(userCartName);
        if (map.size() != 0) {
            for (Map.Entry<Long, CartProductDto> entry : map.entrySet()) {
                cartList.add(entry.getValue());
            }
            return cartList;
        }
        return null;
    }



    @Override
    public void addToCart(CartRequest request) {

        // 获取商品信息
        // 根据productId 查出item
        Item item = itemMapper.selectByPrimaryKey(request.getProductId());

        // item → CartProductDto
        CartProductDto cartProductDto = cartItemConverter.item2Dto(item);
        Integer productNum = request.getProductNum();
        cartProductDto.setProductNum(productNum.longValue());
        cartProductDto.setChecked("true");

        // 加购商品存入redis
        String userCartName = "Cart" + request.getUserId();
        RMap<Long, CartProductDto> map = redissonClient.getMap(userCartName);

         Long productId = request.getProductId();
        // 已存在该商品，更新productNum后put覆盖原信息，不存在直接put
        if (map.get(productId) != null) {
            CartProductDto cartProductDto1 = map.get(productId);
            Long newProductNum = cartProductDto1.getProductNum() + request.getProductNum();

            // 查询限购数量
//            Stock stock = stockMapper.selectStock(productId);
            Stock stock = cartApiClient.getStock(productId);
            if(stock==null||stock.getStockCount()==null){ // 查不到库存信息
                throw new BaseBusinessException(ShoppingRetCode.PARAMETER_NOT_EXIST .getCode(), ShoppingRetCode.PARAMETER_NOT_EXIST .getMessage());
            }
            if(newProductNum>stock.getRestrictCount()||newProductNum>stock.getStockCount()){ // 超卖
                throw new BaseBusinessException(ShoppingRetCode.OVER_BUY_LIMIT.getCode(),ShoppingRetCode.OVER_BUY_LIMIT.getMessage());
            }

            cartProductDto1.setProductNum(newProductNum);
            map.put(request.getProductId(), cartProductDto1);
        }else{
            map.put(request.getProductId(), cartProductDto);
        }

    }

    @Override
    public void updateCartNum(CartRequest request) {

        // 参数校验——限购
        Long productId = request.getProductId();
        Integer productNum = request.getProductNum();

        // 查询限购数量
//        Stock stock = stockMapper.selectStock(productId);
        Stock stock = cartApiClient.getStock(productId);
        if(stock==null||stock.getStockCount()==null){ // 查不到库存信息
            throw new BaseBusinessException(ShoppingRetCode.PARAMETER_NOT_EXIST .getCode(), ShoppingRetCode.PARAMETER_NOT_EXIST .getMessage());
        }
        if(productNum>stock.getRestrictCount()||productNum>stock.getStockCount()){ // 超卖
            throw new BaseBusinessException(ShoppingRetCode.OVER_BUY_LIMIT.getCode(),ShoppingRetCode.OVER_BUY_LIMIT.getMessage());
        }

        // 获取商品信息
        // 根据productId 查出item
        Item item = itemMapper.selectByPrimaryKey(productId);

//         item → CartProductDto
        CartProductDto cartProductDto = cartItemConverter.item2Dto(item);
        cartProductDto.setProductNum(productNum.longValue());
        cartProductDto.setChecked(request.getChecked());

        // 更新redis
        String userCartName = "Cart" + request.getUserId();
        RMap<Long, CartProductDto> map = redissonClient.getMap(userCartName);

        CartProductDto cartProductDto1 = map.get(productId);

        Long newProductNum = request.getProductNum().longValue();


        cartProductDto1.setProductNum(newProductNum);
        cartProductDto1.setChecked(request.getChecked());
        map.put(request.getProductId(), cartProductDto1);

    }


    //全选
    @Override
    public void checkAllCartItem(CheckAllItemRequest request) {

       @NotNull String checked = request.getChecked();

        String userCartName = "Cart" + request.getUserId();

        RMap<Long, CartProductDto> map = redissonClient.getMap(userCartName);

        Set<Long> longs = map.keySet();
        for (Long aLong : longs) {
//            map.get(aLong).setChecked(checked);
            CartProductDto cartProductDto = map.get(aLong);
            cartProductDto.setChecked(checked);
            map.put(aLong,cartProductDto);
        }
    }



    @Override
    public void deleteCartItem(Long uid, Long itemId) {
        //获取Redis
        String userCartName = "Cart" + uid;
        RMap<Long, CartProductDto> map = redissonClient.getMap(userCartName);
        map.remove(itemId);
    }


    @Override
    public void deleteCheckedItem(Long userId) {
        //获取Redis
        String userCartName = "Cart" + userId;
        RMap<Long, CartProductDto > map = redissonClient.getMap(userCartName);
        Set<Long> longs = map.keySet();
        for (Long aLong : longs) {
            CartProductDto cartProductDto = map.get(aLong);
            if ("true".equals(cartProductDto.getChecked())){
                map.remove(aLong);
            }
        }
    }
}
